package system.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import system.common.Arguments;
import system.common.Constants;
import system.dao.DB8_TxLoggingDao;
import system.model.DB8_TxLoggingDto;
import collector.core.CollectConstants;
import collector.core.TaskConstVO;
import collector.core.util.DateUtil;
import collector.core.util.FileUtil;
import collector.task.JobStateVO;

/**
 * <pre>
 * Class : system.service.DB8_TxLoggingService / DB8_TxLoggingService.java
 * 	Define Class Object : 
 * <br>
 * </pre>
 * @author hwanLee / apexcns,Inc.
 * @version 1.2
 * @see javadoc
 * @since 2012. 9. 10.
 */
@Service
public class DB8_TxLoggingService {
	@Autowired
	private DB8_TxLoggingDao db8_TxLoggingDao;

	private static Logger _log = LoggerFactory.getLogger(DB8_TxLoggingService.class);
	private static final String _LogPrefixStr = CollectConstants.LOGGER_MODULE_NAME_SMC + CollectConstants.LOGGER_MODULE_NAME_AFTFIX;//"test Log> ";

	// 코드 수정 [By Lee 2012.09.21]
	public JobStateVO runTxLogging(Arguments arguments, JobStateVO pjsVo, TaskConstVO tcVo) throws IOException, ParseException {
	    JobStateVO jsVo = pjsVo;
	    jsVo.setJobState(CollectConstants.CODE_JOB_STATE_DOING);
	    ExportService.OutputStateLog(jsVo);
	    ExportService.getNextSchedule(jsVo, tcVo, arguments);
	    
		String fileNameSuffix = arguments.getParameter1() + "_" + arguments.getFileName1() + "_" + arguments.getFileName2();
		String historyFileName = tcVo.getTaskPathHistory() + tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix;
		String currentFileName = tcVo.getTaskPathCurrent() + tcVo.getTaskName();
		
		// check for directory
		FileUtil.directoryCheck(tcVo.getTaskPathHistory());
		FileUtil.directoryCheck(tcVo.getTaskPathCurrent());
		
		// delete to current file
		FileUtil.deleteFile(tcVo.getTaskName(), tcVo.getTaskPathCurrent());

		String stepNumber;
		long start;
		long end;
		long recordsCount = 0;
		// 변수 세팅 [By Jeong 2012.09.18]
		float rsTime;
		float fileMakeTime;
		
		File file = null;
		BufferedWriter bufferedWriter = null;
		
		// 변수 세팅 [By Jeong 2012.09.18]
		float totalRsTime = 0;
		float totalFileMakeTime = 0;
		float totalFileCopyTime = 0;
		long totalRecordsCount = 0;
		int totalFilesCount = 0;
		
		List<DB8_TxLoggingDto> tx_logging_list;
		
		String startTime = arguments.getParameter2();
		String endTime = arguments.getParameter3();

		// 조건 데이터 From ~ To 시간 세팅 [By Jeong 2012.09.18]
		jsVo.setJobCondStartTime(startTime);
		jsVo.setJobCondEndTime(endTime);

		if (arguments.getParameter1().equals("DAY")) {
			String tempStartTime = startTime;
			String tempEndTime;

			int roofCount = 24 * jsVo.getJobDurationValue();
			
			Date d;
			DateUtil.setDefaultDateFormat("yyyyMMddHHmm");
			for (int i = 1; i <= roofCount; i++) {
				d = Constants.simDf_Min.parse(startTime);
				tempEndTime = DateUtil.dateAddFormat(Calendar.HOUR, (i * 1), d);
				arguments.setParameter2(tempStartTime, 0);
				if (i == roofCount) {
					arguments.setParameter3(endTime, 0);
				} else {
					arguments.setParameter3(tempEndTime, 0);
				}
				// rs start
				start = System.currentTimeMillis();
				
				tx_logging_list = db8_TxLoggingDao.tx_logging_01_list(arguments);
				
				// 코드 수정 totalRecordsCount [By Jeong 2012.09.18]
				recordsCount = tx_logging_list.size();
				totalRecordsCount += recordsCount;

				end = System.currentTimeMillis();
				rsTime = (end - start) / 1000f;
				// 코드 수정 totalRsTime [By Jeong 2012.09.18]
				totalRsTime += rsTime;
				// rs end
				// file-make start
				start = System.currentTimeMillis();
				
				stepNumber = "000" + i;
				file = new File(historyFileName + "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()) + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
				//file = FileUtil.createFile(historyFileName + "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()) + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
				
				bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

				// 코드 수정 totalFiles [By Jeong 2012.09.18]
				totalFilesCount += ExportService.OutputList(tx_logging_list, bufferedWriter, historyFileName, "_" + stepNumber.substring((stepNumber.length() - 4), stepNumber.length()), 0, tcVo.getTaskName());
				
				end = System.currentTimeMillis();
				 
				fileMakeTime = (end - start) / 1000f;
				// 코드 수정 totalFileMakeTime [By Jeong 2012.09.18]
				totalFileMakeTime += fileMakeTime;
				// file-make end
			
				_log.debug(_LogPrefixStr + "------------------------------------------------------------------------------------");
				_log.debug(_LogPrefixStr + " step-" + i + " :: record(" + recordsCount + "), rs(" + rsTime + "s)");
				_log.debug(_LogPrefixStr + "------------------------------------------------------------------------------------");
				
				d = Constants.simDf_Min.parse(tempEndTime);
				tempStartTime = DateUtil.dateAddFormat(Calendar.MINUTE, 1, d);
			}
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			//file-copy end
		} else {
			// rs start
			start = System.currentTimeMillis();
			
			tx_logging_list = db8_TxLoggingDao.tx_logging_01_list(arguments);
			// 코드 수정 totalRecordsCount [By Jeong 2012.09.18]
			totalRecordsCount += tx_logging_list.size();

			end = System.currentTimeMillis();
			totalRsTime = (end - start) / 1000f;
			// rs end
			// file-make start
			start = System.currentTimeMillis();
			
			file = new File(historyFileName + "_0001" + FileUtil.genFileNumber(0) + Constants.fileNameExtension);
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));

			// 코드 수정 totalFiles [By Jeong 2012.09.18]
			totalFilesCount = ExportService.OutputList(tx_logging_list, bufferedWriter, historyFileName, "_0001", 0, tcVo.getTaskName());
			
			end = System.currentTimeMillis();
			totalFileMakeTime = (end - start) / 1000f;
			// file-make end
			// file-copy start
			start = System.currentTimeMillis();
			
			FileUtil.copyBytes(tcVo.getTaskPathHistory(), tcVo.getTaskName() + "_" + DateUtil.dateToYmd(pjsVo.getScheduleTime(),"yyyyMMddHHmmss") + "_" + fileNameSuffix, currentFileName, Constants.fileNameExtension);

			end = System.currentTimeMillis();
			totalFileCopyTime = (end - start) / 1000f;
			// file-copy end
		}
		
		//jsVo.setJobAuto(jobAuto);
		jsVo.setTotalFileCount(totalFilesCount);
		jsVo.setTotalRecordCount(totalRecordsCount);
		jsVo.setRsTime(totalRsTime);
		jsVo.setFileMakeTime(totalFileMakeTime);
		jsVo.setFileCopyTime(totalFileCopyTime);
		
		jsVo.setSuccDoneResult(CollectConstants.CODE_JOB_RESULT_CODE_SUCC, "do Job Succ State...");

		// 작업 상태 객체 리턴
		return jsVo;
	}
}
